package com.softserveinc.lahire.builders;

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.StringTokenizer;

/**
 * @author Pavlo Lozovskiy
 */
public class PostRequestBuilder extends RequestBuilder {

	private int entityLength;

	public void buildHeaders() {
		String line;
		try {
			do {
				line = in.readLine();
				StringTokenizer tok = new StringTokenizer(line);
				if (tok.hasMoreTokens()) {
					String chunk = (String) tok.nextElement();

					if (chunk.equalsIgnoreCase("Host:")) {
						request.setHost((String) tok.nextElement());

					} else if (chunk.equalsIgnoreCase("Content-Length:")) {
						entityLength = Integer.parseInt((String) tok
								.nextElement());
					}
				}
			} while (line != null && line.trim().length() > 0);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void buildParameters() {

		try {

			char[] cb = new char[entityLength];
			in.read(cb);

			String entity = new String(cb);

			System.out.println(entity);
			String[] pair = entity.split("&");

			HashMap<String, String> parameters = new HashMap<String, String>();

			for (String mapping : pair) {
				String[] map = mapping.split("=");

				if (map.length < 2) {
					parameters.put(map[0], "");
				} else {
					parameters.put(map[0], map[1]);
				}
			}

			request.setParameters(parameters);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
